<template>
  <a-row>
    <a-col :span="4">
      <a-directory-tree v-model:expandedKeys="expandedKeys" :tree-data="departmentData"
        :replaceFields="{ key: 'Id', title: 'Name',value:'Id' }" @select="selectDepartment" />
    </a-col>
    <a-col :span="20">

      <tableLayout :columns="columns" :get="getData" ref="layout" :selectItem="selectItem" :params="params"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <template v-slot:status="item">
          测试-{{ item.value.text.name }}
        </template>
        <template #button>
          <a-button type="primary" style="margin-left: 20px" @click='add'>新增</a-button>
          <a-button style="margin-left: 20px" @click="edit" :disabled="selectedRowKeys.length !== 1">修改</a-button>
          <a-button type="primary" style="margin-left: 20px" danger @click="del"
            :disabled="selectedRowKeys.length !== 1">删除</a-button>
        </template>
        <template #operationMore="item">
          <a @click="edit(null, item.value.record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="del(null, item.value.record.Id)">删除</a>
        </template>
        <template v-slot:custom="data">
          <a-input v-model:value="data.formData[data.key]" />
        </template>
      </tableLayout>
    </a-col>
  </a-row>
  <a-modal :title="formState.Id ? '编辑用户' : '新增用户'" v-model:visible="model_visible" :confirm-loading="confirmLoading"
    @ok="model_handleOk" width="900px">
    <a-form ref="formRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules"
      layout="inline" class="comform">
      <a-form-item label="用户名" style="width: calc(50% - 20px);" class="form__item" name="UserName">
        <a-input v-model:value="formState.UserName" />
      </a-form-item>
      <a-form-item label="密码" style="width: calc(50% - 20px);" class="form__item" name="Password">
        <a-input-password v-model:value="formState.Password" />
      </a-form-item>
      <a-form-item label="姓名" style="width: calc(50% - 20px);" class="form__item" name="RealName">
        <a-input v-model:value="formState.RealName" />
      </a-form-item>
      <a-form-item label="电话号码" style="width: calc(50% - 20px);" class="form__item" name="Mobile">
        <a-input v-model:value="formState.Mobile" />
      </a-form-item>
      <a-form-item label="邮箱" style="width: calc(50% - 20px);" class="form__item" name="Email">
        <a-input v-model:value="formState.Email" />
      </a-form-item>
      <a-form-item label="上级部门" style="width: calc(50% - 20px);" class="form__item" name="DepartmentId">
        <a-tree-select v-model:value="formState.DepartmentId" style="width: 100%"
          :replaceFields="{ children: 'children', title: 'Name', key: 'Id', value: 'Id' }"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="treeData" placeholder="Please select"
          tree-default-expand-all />
      </a-form-item>
      <a-form-item label="状态" style="width: calc(50% - 20px);" class="form__item" name="State">
        <a-radio-group name="radioGroup" v-model:value="formState.State">
          <a-radio :value="1">启用</a-radio>
          <a-radio :value="0">停用</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="角色" style="width: calc(100% - 20px);" class="form__item" name="RoleIdList"
        :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
        <a-transfer :data-source="transferData" show-search :rowKey="record => record.Id" :filter-option="filterOption"
          :target-keys="formState.RoleIdList" :render="item => item.Name" @change="handleChange"
          @search="handleSearch" />
      </a-form-item>
    </a-form>

  </a-modal>

</template>


<script lang="ts">
import { defineComponent, ref, onMounted, onBeforeMount, nextTick, UnwrapRef, reactive, h, VNode } from 'vue';
import { Moment } from 'moment';
import tableLayout from '@/components/tableLayout/tableLayout.vue';
import { SelectEvent } from 'ant-design-vue/es/tree/Tree';
import { getData, setUser, delUser, getRoleData, getDepartmentTreeData } from '@/api/syssetting/user';
import { Layout, message } from 'ant-design-vue';
import { multiply } from 'lodash';
import { valueEquals } from 'element-plus';
import Department from '../department/department.vue';


interface FormState {
  Id: Number;
  UserName: string;
  RealName: string;
  Password: string;
  Mobile: string;
  Email: string;
  State: Number;
  RoleIdList: Number[];
  DepartmentId: string;
}

export default defineComponent({
  name: 'sys_user',
  components: {
    tableLayout
  },
  setup() {
    const layout = ref();
    const transferData = ref([]);
    const departmentData = ref([]);
    const expandedKeys = ref([]);
    const treeData = ref([]);
    let params = ref();

    onMounted(() => {
      getRoleData({}).then(e => {
        transferData.value = e.data.Data;
      }).catch(err => {
        message.error(err.message || "获取角色失败!")
      })

      getDepartmentTreeData({ IsValid: true }).then(e => {
        departmentData.value = treeData.value = e.data.Data
      }).catch(err => {
        message.error(err.message || "获取部门失败!")
      })
    })

    const selectDepartment = (selectedKeys: string[], info: SelectEvent) => {
      params.value = { DepartmentId: selectedKeys[0]};
      nextTick(() => {
        layout.value.getData();
      });
    };

    //列表
    const columns = [
      { title: '序号', dataIndex: 'Id' },
      { title: '用户名', dataIndex: 'UserName' },
      { title: '姓名', dataIndex: 'RealName' },
      { title: '电话号码', dataIndex: 'Mobile' },
      { title: '邮箱', dataIndex: 'Email' },
      {
        title: '状态', dataIndex: 'State', customRender: function ({ text }): VNode {
          return h('div', {
            style: {
              color: 'red'
            }
          }, text == 1 ? '有效' : '无效');
        }
      },
      { title: '更新时间', dataIndex: 'UpdateTime' }
    ]

    //表单对象
    const formState: UnwrapRef<FormState> = reactive({
      Id: 0,
      UserName: '',
      RealName: '',
      Password: '',
      Mobile: '',
      Email: '',
      State: 1,
      RoleIdList: [],
      DepartmentId: ''
    });

    // 筛选
    const selectItem = ref([
      { title: '用户名', key: 'UserName', type: 'input', itemWidth: '290px' },
      { title: '邮箱', key: 'Email', type: 'input', itemWidth: '290px' },
      { title: '姓名', key: 'RealName', type: 'input', itemWidth: '290px' },
      { title: '电话号码', key: 'Mobile', type: 'input', itemWidth: '290px' }
    ])

    // 规则
    const rules = ref({
      UserName: [{ required: true, message: '请输入用户名', trigger: 'change' }],
      RealName: [{ required: true, message: '请输入真实姓名', trigger: 'change' }],
      Password: [{ required: true, message: '请输入密码', trigger: 'change' }]
    });

    const add = () => {
      model_visible.value = true;
      Object.assign(formState, {
        Id: 0,
        UserName: '',
        RealName: '',
        Password: '',
        Mobile: '',
        Email: '',
        State: 1,
        RoleIdList: [],
      });
    }

    const edit = (event: any, item: any) => {
      rules.value.UserName[0].required = false;
      rules.value.Password[0].required = false;
      let selectItem = item;
      if (!selectItem) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
          message.warning('请先选择一条数据!');
          return;
        }
        selectItem = selectedRows.value[0];
      }
      model_visible.value = true;
      Object.assign(formState, selectItem);
    }

    //穿梭框过滤
    const filterOption = (inputValue: string, option: any) => {
      return option.Name.indexOf(inputValue) > -1;
    };

    //穿梭框数据搜索
    const handleSearch = (dir: string, value: string) => {
      // console.log('search:', dir, value);
    };
    //穿梭框数据处理数据
    const handleChange = (keys: Number[], direction: string, moveKeys: string[]) => {
      // console.log(keys, direction, moveKeys);
      formState.RoleIdList = keys;
    };

    const del = (event: any, Id: any) => {
      let selectId = Id;
      if (!selectId) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
          message.warning('请先选择一条数据!');
          return;
        }
        selectId = selectedRowKeys.value[0].Id;
      }
      delUser({ Id: selectId }).then(() => {
        message.success("删除成功!");
        layout.value.getData();
      }).catch(err => {
        message.error(err.message || "删除失败!")
        confirmLoading.value = false;
      })
    }

    const model_visible = ref<boolean>(false);
    const confirmLoading = ref<boolean>(false);
    const formRef = ref()

    const model_handleOk = () => {
      formRef.value.validate().then(() => {
        confirmLoading.value = true;
        setUser(formState).then(e => {
          message.success("添加成功！");
          confirmLoading.value = false;
          model_visible.value = false;
          layout.value.getData();
        }).catch(err => {
          message.error(err.message || "添加失败!")
          confirmLoading.value = false;
        })
      }).catch(() => {
        message.error('请检查必填项是否全部填写!');
      })
    }

    // 多选
    const selectedRowKeys = ref<any[]>([]);
    const selectedRows = ref<any[]>([]);
    const onSelectChange = (keys: [], rows: any) => {
      selectedRowKeys.value = keys;
      selectedRows.value = rows;
    }


    const labelCol = { span: 6 };
    const wrapperCol = { span: 18 };

    return {
      columns, getData, selectItem, model_visible, confirmLoading, model_handleOk, add, edit, del,
      formState, labelCol, wrapperCol, selectedRowKeys, onSelectChange, rules, layout, formRef, filterOption,
      handleSearch, handleChange, transferData, departmentData, expandedKeys, treeData, selectDepartment,params
    }
  }
})
</script>

<style lang="scss" scoped>
.comform {
  & .form__item {
    margin-bottom: 16px;

    & .ant-form-item-label {
      flex-grow: 1 !important;
      flex-shrink: 0;
    }
  }
}
</style>
<style lang="scss">
.comform {
  & .form__item {
    margin-bottom: 16px;

    & .ant-form-item-label {
      flex-grow: 1;
      flex-shrink: 0;
    }
  }
}
</style>